﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;

namespace Halfwit.Controls
{
    public class DropDownButton : ToggleButton
    {
        // *** Dependency Properties *** 
        public static readonly DependencyProperty DropDownProperty
            = DependencyProperty.Register("DropDown", typeof(ContextMenu), typeof(DropDownButton), new UIPropertyMetadata(DropDownChanged));

        // *** Constructors *** 
        public DropDownButton()
        {
            // Bind the ToogleButton.IsChecked property to the drop-down's IsOpen property 
            Binding binding = new Binding("DropDown.IsOpen");
            binding.Source = this;
            this.SetBinding(IsCheckedProperty, binding);
        }

        static void DropDownChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var ddb = d as DropDownButton;
            if (ddb == null) return;

            var cm = e.NewValue as ContextMenu;
            if (cm == null) return;

            cm.PlacementTarget = ddb;
            cm.Placement = PlacementMode.Bottom;
        }

        // *** Properties *** 
        public ContextMenu DropDown
        {
            get
            {
                return (ContextMenu)GetValue(DropDownProperty);
            }
            set
            {
                SetValue(DropDownProperty, value);
            }
        }
    }
}
